#! C:\Perl\bin\perl.exe

# Copyright (c) 2010, College Center for Library Automation

# See the included Copyright.txt file for full license

#
#
#

use strict;
use warnings;

use LWP::UserAgent;
use HTTP::Request;
use HTTP::Request::Common;
use Date::Calc qw(Decode_Month Add_Delta_YM Add_Delta_Days Today);
use Text::CSV;

use avsCommon;


dbsetup();

my ($content, $response, $request, $url);
my $session;

# create user agent, set cookies
my $ua = new LWP::UserAgent(keep_alive=>1);
$ua->cookie_jar( {} );
$ua->env_proxy;

# set credentials
$ua->credentials('stats.jstor.org:80', 'AdminAuthorization', $vendorusername, $vendorpassword);

# loop through all the colleges
do {
	getStats ();
} while $sthlogin->fetch;

dbshutdown();

exit();

sub getStats {
	$url="http://stats.jstor.org/cgi-bin/admin/stats?brief";

	$request = HTTP::Request->new(POST => $url);
	$request->content_type('application/x-www-form-urlencoded');
	$request->content("byPerm=$username&byYear1=$begyear&byMonth1=$begmonth&byYear2=$endyear&byMonth2=$endmonth&byText=1&bySub=Submit+Request");

	$response = $ua->request($request);
	if (substr($response->status_line,0,3) eq '500') {
		print "#info: timeout retry\n";
		sleep 5;
		$response = $ua->request($request);
	};
	if (!$response->is_success) {
		die "#error:$0: POST report $url : " . $response->status_line;
	};

	$content = $response->decoded_content;

	# save contents for possible debugging
	savecontent('Jstor', "$collegeid", $content);


	$content =~ /total \n(?<data>.*?)totals/s;
	my $data = $+{data};
	$data =~ s/ //g; # remove spaces

	my $period = myperiod($begyear, $begmonth);

	while ($data =~ /.*?(?<year>\d{4})\/(?<month>\d{2})(\|\d+){9}\|(?<searches>\d+)/sgc) {
		my $period = myperiod($+{year}, $+{month});
		my $searches = $+{searches};
		print "$vendorid $collegeid $period 'Jstor' 0 $searches\n";
		$sthstats->execute($vendorid, $collegeid, 'Jstor', $period, $searches, 2)
			or die '#error: sthstats execute failed';
	}
}